package cn.edu.dgut.exp03.services;

import cn.edu.dgut.exp03.models.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.*;

@Service
public class RegionService implements InitializingBean {
    /**
     * 数据源url
     */
    private static final String CORONA_VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final List<RegionStats> allRegionStats = new ArrayList<>();

    public List<RegionStats> getAllRegionStats() { return allRegionStats; }

    @Scheduled(cron="${xzx.Scheduled.updateData}")
    public void fetchCoronaVirusData() throws IOException {

        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        InputStream inputStream = body.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        Reader in = new BufferedReader(reader);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        for (CSVRecord record : records) {

            //获取数据
            RegionStats region = new RegionStats();

            region.setState(record.get(0));
            region.setCountry(record.get(1));
            int case1 = Integer.parseInt(record.get(record.size() - 1));
            region.setLatestTotalCases(case1);
            int case2 = Integer.parseInt(record.get(record.size() - 2));
            int case3 = case1 - case2;
            region.setDiffFromPrevDay(case3);
            allRegionStats.add(region);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception{
        fetchCoronaVirusData();
    }
}
